package com.yyk.yiliao.ui.shop.fragment;

import android.os.Bundle;
import android.os.Handler;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.widget.EndLessOnScrollListener;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseFragment;
import com.yyk.yiliao.base.BaseRecyclerAdapter;
import com.yyk.yiliao.base.BaseRecyclerHolder;
import com.yyk.yiliao.ui.activity.detail.activity.Detail_Activity;
import com.yyk.yiliao.widget.diver.more.SpacesItemDecoration;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.util.CheckDecimalPointUtil;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.bean.CartAddcart;
import com.yyk.yiliao.bean.ShopGoodslist_Info;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by ${zk} on 2018/8/6 0006.
 */

public class ShopTab_Fragment extends BaseFragment {
    public static final String ARGS_PAGE = "ShopTab_Fragment";
    @BindView(R.id.nTab_rv)
    RecyclerView nTab_rv;
    @BindView(R.id.null_data)
    RelativeLayout nullData;

    private String cid;
    private BaseRecyclerAdapter<ShopGoodslist_Info.DataBean> adapter;
    List<ShopGoodslist_Info.DataBean> shopList = new ArrayList<>();
    private int pageIndex;

    public static ShopTab_Fragment newInstance(int page) {
        Bundle args = new Bundle();
        args.putInt(ARGS_PAGE, page);
        ShopTab_Fragment fragment = new ShopTab_Fragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_hospital_tab;
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {
        initGetIntent();
        initPost();
        initAdapter();

    }

    private void initPost() {
        pageIndex = 1;
        initShopList(Integer.parseInt(cid), true, pageIndex);
    }

    private void initGetIntent() {
        Bundle arguments = getArguments();
        cid = arguments.getString("hha");
//        Logger.e("商城  底部  切换 id————" + cid);
    }

    private void initAdapter() {
        adapter = new BaseRecyclerAdapter<ShopGoodslist_Info.DataBean>(getActivity(), shopList, R.layout.adapter_item_hospital_tab) {
            @Override
            public void convert(final BaseRecyclerHolder holder, final ShopGoodslist_Info.DataBean item, int position, boolean isScrolling) {
                holder.setText(R.id.b_hospital_name, item.getName());
                String money = CheckDecimalPointUtil.checkPoint(item.getMoney());
                holder.setText(R.id.b_grade, "¥ " + money);
                holder.setImageByUrl(R.id.b_picture, ApiService.BASE_URL + item.getPic());
                holder.getView(R.id.b_addNumber).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setBuyShop(item.getId(), (LinearLayout) holder.getView(R.id.b_addNumber), item.getPic() + "");
                    }
                });
            }
        };
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2, LinearLayoutManager.VERTICAL, false);
        nTab_rv.setLayoutManager(gridLayoutManager);
        nTab_rv.addItemDecoration(new SpacesItemDecoration(24, 28));
        nTab_rv.setAdapter(adapter);

        nTab_rv.addOnScrollListener(new EndLessOnScrollListener(gridLayoutManager) {
            @Override
            public void onLoadMore(int currentPage) {
//                if (pageIndex == currentPage) {
//                    return;
//                }
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        //请求网络
                        pageIndex++;
                        initShopList(Integer.parseInt(cid), false, pageIndex);

                    }
                }, 1000);
            }
        });

        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position) {
                //商品ID
                Bundle bundle = new Bundle();
                bundle.putInt("id", shopList.get(position).getId());
                startAct(Detail_Activity.class, bundle);
            }
        });
    }

    /**
     * 商品列表
     *
     * @param cid
     */
    private void initShopList(int cid, final boolean flag, int page) {
        Map<String, String> map = new TreeMap<>();

        map.put("page", page + "");
        map.put("cid", cid + "");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postShopGoodlist(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new Subscriber<ShopGoodslist_Info>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(ShopGoodslist_Info info) {
                        Logger.e("商城底部商品列表" + info.toString());
                        if (flag) {
                            shopList.clear();
                        }
                        if (info.getData() != null && info.getData().size() > 0) {
                            shopList.addAll(info.getData());
                        }
                        adapter.notifyDataSetChanged();
                    }

                });

    }

    /**
     * 购买商品
     *
     * @param id
     */
    private void setBuyShop(int id, final LinearLayout buy, final String pic) {
        Map<String, String> map = new TreeMap<>();

        map.put("uid", Hawk.get("uid", 0) + "");
        map.put("gid", id + "");
        map.put("num", "1");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postCartAddcart(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<CartAddcart>() {

                    @Override
                    public void onCompleted() {
                        //完成的时候调用
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();

                    }

                    @Override
                    public void onNext(CartAddcart info) {
                        Logger.e("商品详情加入购物车" + info.getCode());
                        if (info.getCode() == 1) {
                            ShoppingMall_Fragment.intanse.reshefeshShopNumber(buy, pic);
//                            ToastUtil.showShort(getActivity(), "添加成功");
                        } else if (info.getCode() == 101) {
                            ToastUtil.showShort(getActivity(), "没有该商品 ");
                        } else if (info.getCode() == 102) {
                            ToastUtil.showShort(getActivity(), "插入失败 ");
                        } else if (info.getCode() == 103) {
                            ToastUtil.showShort(getActivity(), "购物车已存在 ");
                        } else if (info.getCode() == 104) {
                            ToastUtil.showShort(getActivity(), "商品数量修改失败 ");
                        } else {
                            ToastUtil.showShort(getActivity(), "商品删除失败 ");
                        }
                    }
                });
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        super.onFragmentVisibleChange(isVisible);
        if (isVisible) {
        }
    }
}
